package top.caozj;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import top.caozj.conf.AppConfig;
import top.caozj.conf.DataQuery;
import top.caozj.conf.Datasource;
import top.caozj.conf.MqttConf;
import top.caozj.task.MqttUpload;
import top.caozj.task.QueryDataTask;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Hello world!
 * 从数据库中查询的数据必须为感器，数值，时间
 */
@Log4j2
public class App 
{

    public static void main( String[] args )
    {
        try{
            AppConfig.init("conf/conf.json");
            AppConfig.initSensorMap("conf/map.csv");
            // 创建一个 Timer 实例
            Timer timer = new Timer();

            // 创建一个 TimerTask 实例
            TimerTask task = new TimerTask() {
                @Override
                public void run() {

                    try {
//                        MqttUpload  mqttUpload = new MqttUpload();
//                        mqttUpload.run();
                        QueryDataTask queryDataTask = new QueryDataTask();
                        queryDataTask.run();

                    } catch (Exception e) {
                        log.error(e.getMessage());
                        System.exit(-1);
                        //throw new RuntimeException(e);
                    }

                }
            };

            // 安排任务在指定延迟后开始，并以固定的时间间隔重复执行
            long delay = 0; // 延迟 0 毫秒开始

            //delay为当前时间到下一个整十分钟的时间间隔
            long currentMillis = System.currentTimeMillis();
            long minutes = (currentMillis / (1000 * 60)) % 10;
            delay = (10 - minutes) * 60 * 1000 - (currentMillis % (1000 * 60));

            delay += 5*3600; // 在计算出的整点时间上再延迟5分钟,给数据库足够的时间反应

            log.info("timer start,delay {}s", delay / 1000);

            //long period = AppConfig.TASK_INTERVAL* 60L*1000; // 每 1000 毫秒（1 秒）执行一次
            //测试

            long period = AppConfig.TASK_INTERVAL* 1000L*60;


//           调试时让delay不为0
            if ( AppConfig.DEBUG){
                delay=0;
                period=2000;

            }
            log.info("timer start,per {}s execute once", period / 1000);

            timer.scheduleAtFixedRate(task, delay, period);

        }catch (Exception e){
            log.error(e.getMessage());
            //e.printStackTrace();
        }

    }
}
